package com.aiapphub.SystemCode.controller;
 
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.aiapphub.BaseCode.common.ResponseResult;
import com.aiapphub.BaseCode.constants.AppHttpCodeEnum;
import com.aiapphub.BaseCode.exception.SystemException;
import com.aiapphub.BaseCode.utils.BeanCopyUtils;
import com.aiapphub.BaseCode.utils.WebUtils;
import com.aiapphub.BaseCode.vo.PageVo;
import com.aiapphub.SystemCode.dto.UploadLogDto;
import com.aiapphub.SystemCode.easyExcel.listeners.FileInfoListener;
import com.aiapphub.SystemCode.easyExcel.model.exportExcel.FileInfoExportExcel;
import com.aiapphub.SystemCode.easyExcel.model.importExcel.FileInfoImportExcel;
import com.aiapphub.SystemCode.entity.FileInfo;
import com.aiapphub.SystemCode.service.UploadLogService;
import org.springframework.beans.factory.annotation.Autowired;
import com.aiapphub.SystemCode.service.FileInfoService;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;


/**
 * 上传日志表(UploadLogs)表控制层
 *
 * @author makejava
 * @since 2023-07-18 10:42:48
 */
@RestController
@Slf4j
@CrossOrigin
@RequestMapping("/fileInfo")
public class FileInfoController {
    /**
     * 服务对象
     */
    @Autowired
    private FileInfoService fileInfoService;

    @Autowired
    private UploadLogService uploadLogService;



    /**
     * 查询所有信息
     * @return
     */
    @GetMapping("/listAll")
    public ResponseResult listAllInfo(){

        List<FileInfo> list = fileInfoService.list();
        return ResponseResult.okResult(list);
    }

   /**
   * 分页查询
   * @param pageNum 查询页数
   * @param pageSize 每页大小
   * @return
   */
   @GetMapping("/page/{pageNum}/{pageSize}")
   public ResponseResult getPageInfo(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
       PageVo pageVo = fileInfoService.selectUploadFilePage(pageNum, pageSize);
       return ResponseResult.okResult(pageVo);
   }

    @GetMapping("/list")
    public ResponseResult list(FileInfo fileInfo, Integer pageNum, Integer pageSize){
        PageVo pageVo =  fileInfoService.selectCategoryPage(fileInfo,pageNum,pageSize);
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseResult selectOne(@PathVariable Long id) {
       FileInfo fileInfo = fileInfoService.getById(id);
       return  ResponseResult.okResult(fileInfo);
    }

    /**
     * 新增数据
     *
     * @param fileInfo 实体对象
     * @return 新增结果
     */
    @PostMapping
    public ResponseResult insert(@RequestBody FileInfo fileInfo) {
        fileInfoService.save(fileInfo);
        return ResponseResult.okResult();
    }

    /**
     * 修改数据
     *
     * @param fileInfo 实体对象
     * @return 修改结果
     */
    @PutMapping
    public ResponseResult update(@RequestBody FileInfo fileInfo) {
        fileInfoService.updateById(fileInfo);
        return ResponseResult.okResult();
    }


    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseResult delete(@PathVariable("id") Long id) {
        fileInfoService.removeById(id);
        return ResponseResult.okResult();
    }


    /***
     * 批量删除数据
     * @param ids
     * @return
     */
    @DeleteMapping("/batch")
    public ResponseResult deleteBatch(@RequestBody List<Long> ids) {
        fileInfoService.removeBatchByIds(ids);
        return ResponseResult.okResult();
    }

    /*****
     * 导出全量数据
     * @param response
     */
    @GetMapping("/allExport")
    public void allExport(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("上传日志.xlsx",response);
            //获取需要导出的数据
            List<FileInfo> fileInfo = fileInfoService.list();

            List<FileInfoExportExcel> uploadLogExportExcels = BeanCopyUtils.copyBeanList(fileInfo, FileInfoExportExcel.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), FileInfoExportExcel.class).autoCloseStream(Boolean.FALSE).sheet("日志信息")
                    .doWrite(uploadLogExportExcels);
        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.INTERNAL_SERVER_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }

    /****
     * 根据选择ID批量导出数据
     * @param ids
     * @param response
     */
    @GetMapping("/batchExport")
    public void batchExport(@RequestParam("ids") List<Long> ids, HttpServletResponse response) {
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("上传日志.xlsx", response);

            //根据前端传递的ID列表获取需要导出的数据
            List<FileInfo> fileInfo = fileInfoService.getByIds(ids);

            List<FileInfoExportExcel> uploadLogExportExcels = BeanCopyUtils.copyBeanList(fileInfo, FileInfoExportExcel.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), FileInfoExportExcel.class).autoCloseStream(Boolean.FALSE).sheet("日志信息")
                    .doWrite(uploadLogExportExcels);
        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.INTERNAL_SERVER_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }

    @PostMapping("/batchImport")
    public ResponseResult batchImport (@RequestParam("file") MultipartFile file) {

        try {
            // 判断文件类型是否正确
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
            if (!".xls".equalsIgnoreCase(fileType) && !".xlsx".equalsIgnoreCase(fileType)) {
                throw new SystemException(AppHttpCodeEnum.FORMAL_ERROR);
            }
            // 解析第一个 sheet 页
            EasyExcel.read(file.getInputStream(), FileInfoImportExcel.class, new FileInfoListener()).sheet().doRead();
            saveUploadLog(file.getOriginalFilename(), 0); // 0 表示成功
            return ResponseResult.okResult();
        } catch (IOException e) {
            e.printStackTrace();
            saveUploadLog(file.getOriginalFilename(), 1); // 1 表示失败
            throw  new SystemException(AppHttpCodeEnum.INTERNAL_SERVER_ERROR);
        }
    }


    /**
     * 保存上传日志记录
     * @param fileName 上传的文件名
     * @param uploadStatus 上传状态，1 表示成功，0 表示失败
     */
    private void saveUploadLog(String fileName, int uploadStatus) {
        UploadLogDto uploadLogDto = new UploadLogDto();
        uploadLogDto.setFileName(fileName);
        uploadLogDto.setUploadStatus(uploadStatus);
        uploadLogDto.setUploadTime(new Date());
        uploadLogService.saveUploadLog(uploadLogDto);
    }

}
